package cn.changeforyou.web.cloud.webBase.utils.bean;

import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.Type;

/**
 * 泛型工具
 */
public class GenericityUtil {

    /***
     * 寻找java类的父接口或者祖父接口中的泛型信息
     * @param source 当前类
     * @param target 需要发现的带泛型的类
     * @param genericityIndex 泛型的索引
     * @return
     */
    public static Class findGenericityFromParentOrGrandFather(Class source, Class target, int genericityIndex) {
        Class result = findGenericityFromParent(source, target, genericityIndex);
        if (null == result) {
            Class[] interfaces = source.getInterfaces();
            if (null != interfaces) {
                for (Class anInterface : interfaces) {
                    result = findGenericityFromParent(anInterface, target, genericityIndex);
                    if (null != result) {
                        return result;
                    }
                }
            }
        }
        return null;
    }

    private static Class findGenericityFromParent(Class source, Class target, int genericityIndex) {
        Type[] genericInterfaces = source.getGenericInterfaces();
        for (Type type : genericInterfaces) {
            if (type instanceof ParameterizedTypeImpl) {
                ParameterizedTypeImpl parameterizedTypeImpl = (ParameterizedTypeImpl) type;
                if (parameterizedTypeImpl.getRawType() == target) {
                    Type dtoType = parameterizedTypeImpl.getActualTypeArguments()[genericityIndex];
                    return (Class) dtoType;
                }
            }
        }
        return null;
    }
}
